/**
 *
 * EXTJS 4 模式的admin管理页面公共JS环境，工具
 * Created by yangyan on 2014/8/13 .
 */

/**
 * 自定义的常用函数
 */
F = {
    /**
     * 获取基于项目根路径的完整URL
     * @param url
     * @returns {*}
     */
    url: function (url) {
        var fullUrl = BASE_URL + url;
        return fullUrl;
    },
    rmb: function (price) {
        return '<span class="rmb">¥</span> ' + price + " <span class='rmbUnit'>元</span>";
    },
    /**
     * js本地图片预览，兼容ie[6-9]、火狐、Chrome17+、Opera11+、Maxthon3
     * @param fileObj
     * @param imgPreviewId
     * @param divPreviewId
     */
    previewImage: function (fileObj, imgPreviewId, divPreviewId) {
        var browserVersion = window.navigator.userAgent.toUpperCase();
        if (fileObj.files) {//HTML5实现预览，兼容chrome、火狐7+等
            if (window.FileReader) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    document.getElementById(imgPreviewId).setAttribute("src", e.target.result);
                }
                reader.readAsDataURL(fileObj.files[0]);
            } else if (browserVersion.indexOf("SAFARI") > -1) {
                alert("不支持Safari6.0以下浏览器的图片预览!");
            }
        } else if (browserVersion.indexOf("MSIE") > -1) {
            if (browserVersion.indexOf("MSIE 6") > -1) {//ie6
                document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);
            } else {//ie[7-9]
                fileObj.select();
                if (browserVersion.indexOf("MSIE 9") > -1)
                    fileObj.blur();//不加上document.selection.createRange().text在ie9会拒绝访问
                var newPreview = document.getElementById(divPreviewId + "New");
                if (newPreview == null) {
                    newPreview = document.createElement("div");
                    newPreview.setAttribute("id", divPreviewId + "New");
                    newPreview.style.width = document.getElementById(imgPreviewId).width + "px";
                    newPreview.style.height = document.getElementById(imgPreviewId).height + "px";
                    newPreview.style.border = "solid 1px #d2e2e2";
                }
                newPreview.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='" + document.selection.createRange().text + "')";
                var tempDivPreview = document.getElementById(divPreviewId);
                tempDivPreview.parentNode.insertBefore(newPreview, tempDivPreview);
                tempDivPreview.style.display = "none";
            }
        } else if (browserVersion.indexOf("FIREFOX") > -1) {//firefox
            var firefoxVersion = parseFloat(browserVersion.toLowerCase().match(/firefox\/([\d.]+)/)[1]);
            if (firefoxVersion < 7) {//firefox7以下版本
                document.getElementById(imgPreviewId).setAttribute("src", fileObj.files[0].getAsDataURL());
            } else {//firefox7.0+
                document.getElementById(imgPreviewId).setAttribute("src", window.URL.createObjectURL(fileObj.files[0]));
            }
        } else {
            document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);
        }

    },
    openPage:function(v){
        return "[<a href='" + v + "' target='_blank'>[ 打开浏览 ]</a>]";
    },
    required:'<span style="color:red;font-weight:bold" data-qtip="Required">*</span>',
    highlightRed:function(v){
        return '<span style="color:#ff0000;font-weight:bold">' + v + '</span>';
    },
    highlightBlue:function(v){
        return '<span style="color:#0000ff;font-weight:bold">' + v + '</span>';
    },
    highlightGreen:function(v){
        return '<span style="color:#009900;font-weight:bold">' + v + '</span>';
    },
    highlightGray:function(v){
        return '<span style="color:#660000;font-weight:bold">' + v + '</span>';
    },
    highlightPurple:function(v){
        return '<span style="color:#770088;font-weight:bold">' + v + '</span>';
    },
    highlightYellow:function(v){
        return '<span style="color:#D35400;font-weight:bold">' + v + '</span>';
    }
};
//处理键盘事件 禁止后退键（Backspace）密码或单行、多行文本框除外
function banBackSpace(e) {
    var ev = e || window.event;//获取event对象
    var obj = ev.target || ev.srcElement;//获取事件源
    var t = obj.type || obj.getAttribute('type');//获取事件源类型
    //获取作为判断条件的事件类型
    var vReadOnly = obj.readOnly;
    var vDisabled = obj.disabled;
    //处理undefined值情况
    vReadOnly = (vReadOnly == undefined) ? false : vReadOnly;
    vDisabled = (vDisabled == undefined) ? true : vDisabled;
    //当敲Backspace键时，事件源类型为密码或单行、多行文本的，
    //并且readOnly属性为true或disabled属性为true的，则退格键失效
    var flag1 = ev.keyCode == 8 && (t == "password" || t == "text" || t == "textarea") && (vReadOnly == true || vDisabled == true);
    //当敲Backspace键时，事件源类型非密码或单行、多行文本的，则退格键失效
    var flag2 = ev.keyCode == 8 && t != "password" && t != "text" && t != "textarea";
    //判断
    if (flag2 || flag1)return false;
}
//禁止退格键 作用于Firefox、Opera
document.onkeypress = banBackSpace;
//禁止退格键 作用于IE、Chrome
document.onkeydown = banBackSpace;

(function () {
    if (window.Ext == undefined) {
        return;
    }
//EXTJS 空白图片
    Ext.BLANK_IMAGE_URL = F.url('/resources/extjs4/s.gif');
    Ext.form.Labelable.prototype.msgTarget = 'qtip';
    Ext.form.field.Date.prototype.format = "Y-m-d";
    Ext.grid.Panel.prototype.loadMask = true;
    Ext.grid.Panel.prototype.enableTabScroll = true;
    Ext.form.field.ComboBox.prototype.forceSelection = true;
//Ext.form.field.ComboBox.prototype.queryParam = "keywords";
    Ext.window.Window.prototype.constrain = true;
    Ext.tip.QuickTipManager.init();
    Ext.Ajax.defaultHeaders = {
        'Powered-By': 'ND'
    };
    Ext.QuickTips.init();
    /**
     * 设置自动extjs load参数
     */
    Ext.Loader.setConfig({
        enabled: true,
        paths: {
            'Ext': F.url('/resources/extjs4'),
            'manager': F.url('/static/manager')
        }
    });

    /**
     * AJAX request 提交失败后
     */
    window.ajax_failed = function (response, opts) {
        var obj = Ext.decode(response.responseText);
        if (!obj.success) {
            UI.showErrorMsg('AJAX请求失败', obj.error);
        }
    };

    /**
     * AJAX from 提交失败后
     */
    window.ajax_form_failed = function (form, action) {
        switch (action.failureType) {
            case Ext.form.Action.CLIENT_INVALID:
                UI.showErrorMsg('表单验证提示',
                    '划红线的部分表示没有符合的内容有误，请根据提示修正');
                break;
            case Ext.form.Action.CONNECT_FAILURE:
                UI.showErrorMsg('网络提示', '网络连接异常，请检查网络');
                break;
            case Ext.form.Action.SERVER_INVALID:
                UI.showErrorMsg("错误", action.result.error);
        }
    };
    var msgCt;
    window.UI = {
        /**
         * 提示消息
         * @param title
         * @param msg
         */
        showInfoMsg: function (title, msg) {
            if (arguments.length == 1) {
                msg = title;
                title = "提示";
            }
            if (!msgCt) {
                msgCt = Ext.DomHelper.insertFirst(top.document.body, {id: 'msg-div'}, true);
            }
            var m = Ext.DomHelper.append(msgCt, '<div class="msg"><h3>' + title + '</h3><p>' + msg + '</p></div>', true);
            m.hide();
            m.slideIn('t').ghost("t", {delay: 3000, remove: true});
        },
        /**
         * 呈现警告消息提示
         * @param msg
         */
        showWarnMsg: function (title, msg) {
            if (arguments.length == 1) {
                msg = title;
                title = "警告信息";
            }
            if (!msgCt) {
                msgCt = Ext.DomHelper.insertFirst(top.document.body, {id: 'msg-div'}, true);
            }
            var m = Ext.DomHelper.append(msgCt, '<div class="msg warn"><h3>' + title + '</h3><p>' + msg + '</p></div>', true);
            m.hide();
            m.slideIn('t').ghost("t", {delay: 6000, remove: true});
        },
        /**
         * 呈现错误消息提示
         * @param msg
         */
        showErrorMsg: function (title, msg) {
            if (arguments.length == 1) {
                msg = title;
                title = "发生错误";
            }
            if (!msgCt) {
                msgCt = Ext.DomHelper.insertFirst(top.document.body, {id: 'msg-div'}, true);
            }
            var m = Ext.DomHelper.append(msgCt, '<div class="msg error"><h3>' + title + '</h3><p>' + msg + '</p></div>', true);
            m.hide();
            m.slideIn('t').ghost("t", {delay: 8000, remove: true});
        },
        /**
         * 呈现成功消息提示
         * @param msg
         */
        showSuccessMsg: function (title, msg) {
            if (arguments.length == 1) {
                msg = title;
                title = "操作成功";
            }
            if (!msgCt) {
                msgCt = Ext.DomHelper.insertFirst(top.document.body, {id: 'msg-div'}, true);
            }
            var m = Ext.DomHelper.append(msgCt, '<div class="msg success"><h3>' + title + '</h3><p>' + msg + '</p></div>', true);
            m.hide();
            m.slideIn('t').ghost("t", {delay: 4000, remove: true});
        }
    };

    /**
     * 可勾选的树
     */
    Ext.define('Admin.common.CheckableTreePanel', {
        extend: 'Ext.tree.Panel',
//    requires: [
//        'Ext.data.TreeStore'
//    ],
//    xtype: 'check-tree',

        requires: [
            'Ext.data.*',
            'Ext.grid.*',
            'Ext.tree.*',
            'Ext.ux.CheckColumn'
        ],
        xtype: 'tree-grid',
        rootVisible: false,
//    useArrows: true,
        autoLoad: false,

        initComponent: function () {
            var _this = this;
            var recursiveSetCheck = function (child, checked) {
                if (child.hasChildNodes()) {
                    child.eachChild(function (c) {
                        if (c.get('leaf')) {
                            c.set('checked', checked);
                        } else {
                            recursiveSetCheck(c, checked);
                        }
                    });
                }
            };
            this.recursiveSetCheck = recursiveSetCheck;
            var menu = this.menu = Ext.create('Ext.menu.Menu', {
                width: 100,
                margin: '0 0 10 0',
                items: [
                    {
                        text: '全选',
                        handler: function () {
                            recursiveSetCheck(_this.getSelectionModel().getLastSelected(), true);
                        }
                    },
                    {
                        text: '取消全选',
                        handler: function () {
                            recursiveSetCheck(_this.getSelectionModel().getLastSelected(), false);
                        }
                    }
                ]
            });


            Ext.apply(this, {
                listeners: {
                    itemcontextmenu: function (treeview, record, item, index, e, eOpts) {
                        e.stopPropagation();
                        e.preventDefault();
                        if (record.get('leaf')) {
                            return;
                        } else {
                            menu.showAt(e.getXY());
                        }
                    }
                }
            });
            this.callParent();
        },
        allUncheck: function () {
            this.recursiveSetCheck(this.getRootNode(), false);
        }
    });
})();


